<template>
  <el-form
    :model="ruleForm"
    :rules="rules"
    ref="ruleForm"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="账号" prop="account">
      <el-input v-model="ruleForm.account" placeholder="请输入账号"></el-input>
    </el-form-item>
    <el-form-item v-if="type == 'add' ? 1 : 0" label="密码" prop="password">
      <el-input v-model="ruleForm.password" placeholder="请输入密码"></el-input>
    </el-form-item>
    <el-form-item label="用户组" prop="userGroup">
      <el-select v-model="ruleForm.userGroup" placeholder="请选择用户组">
        <el-option label="超级管理员" value="超级管理员"></el-option>
        <el-option label="普通管理员" value="普通管理员"></el-option>
      </el-select>
    </el-form-item>
    <div class="btn">
      <el-button  v-if="type == 'add' ? 1 : 0" @click="submit" type="primary">添加</el-button>
      <el-button v-if="type == 'add' ? 1 : 0" @click="reset('ruleForm')">重置</el-button>
      <el-button v-if="type == 'add' ? 0 : 1" @click="cancel">取 消</el-button>
      <el-button v-if="type == 'add' ? 0 : 1" type="primary" @click="submit">确 定</el-button>
    </div>
  </el-form>
</template>

<script>
export default {
  props: {
    type: {
      type: String,
      default: "add",
    },
    defaultForm: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      labelPosition: "right",
      ruleForm: {
        account: "",
        password: "",
        userGroup: "",
        dialogFormVisible:false
      },
      rules: {
        account: [
          { required: true, message: "请输入原密码", trigger: "change" },
          {
            pattern: /^[a-zA-Z\d]+$/,
            message: "请输入正确格式账号",
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "请输入新密码", trigger: "change" },
          {
            pattern: /^[a-zA-Z\d]+$/,
            message: "请输入正确格式密码",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    reset(formName) {
      this.$refs[formName].resetFields();
    },

    submit(){
        this.$refs.ruleForm.validate((res) => {
        // console.log("验证规则是否正确", res);
        if (res) {
          this.$emit("ruleForm", this.ruleForm);
        }
      });
    },

    cancel(){
      this.$emit("ruleForm1", this.ruleForm);
    }
  },

   watch: {
    defaultForm: {
      handler: function () {
        if (this.type === "list") {
            console.log('123');
          this.ruleForm = { ...this.defaultForm };
        }
      },
      immediate: true
    },
  },
};
</script>

<style lang="less" scoped>
</style>